<?php

namespace App\Http\Controllers\Api;

use App\Models\Product;
use App\Models\ProductPes;
use App\Transformers\ProductPesTransformer;
use GuzzleHttp\Client;
use Illuminate\Http\Request;

class ProductPesController extends Controller
{
    public function getGoodsDateInfo()
    {
        $http = new Client();
        $response = $http->get('https://www.yzkj01.com/notice/get_goods_date_info');
        $result = json_decode($response->getBody(), true);
        foreach ($result as $item) {
            if ($item['goods_name'] !== '') {
                $product = Product::where('title', $item['goods_name'])->first();
                if ($product) {
                    $productPes = new ProductPes;
                    $productPes->production_date = $item['production_date'];
                    $productPes->expiration_date = $item['expiration_date'];
                    $productPes->stock = $item['stock'];
                    if ($item['stock'] < 0) {
                        $productPes->registered_stock = 0;
                    } else {
                        $productPes->registered_stock = $item['stock'];
                    }
                    $productPes->warehouse_id = 1;
                    $productPes->created_at = $item['add_time'];
                    $productPes->updated_at = $item['update_time'];
                    $productPes->product()->associate($product);
                    $productPes->save();
                }
            }
        }
        return $this->response->created();
    }

    public function store(Request $request, ProductPes $productPes, ProductPesTransformer $productPesTransformer)
    {
        $user = $this->user();
        $productPes->fill($request->all());
        $productPes->user()->associate($user);
        $productPes->save();

        return $this->response->item($productPes, $productPesTransformer)->setStatusCode(201);
    }

    public function show(ProductPes $productPes, ProductPesTransformer $productPesTransformer)
    {
        return $this->response->item($productPes, $productPesTransformer);
    }

    public function index(ProductPes $productPes, ProductPesTransformer $productPesTransformer)
    {
        $productPesList = $productPes->recent()->paginate(5);
        return $this->response->paginator($productPesList, $productPesTransformer);
    }

    public function update(ProductPes $productPes, Request $request, ProductPesTransformer $productPesTransformer)
    {
        $productPes->update($request->all());
        return $this->response->item($productPes, $productPesTransformer);
    }

    public function destroy(ProductPes $productPes)
    {
        $productPes->delete();
        return $this->response->noContent();
    }
}
